<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="25%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '@/components/Form/index';
import { dataScopeFormSchema } from '../menu.data';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { useMessage } from '@/hooks/web/useMessage';
import { edit, add } from '@/api/sys/sysDataScopeManage';
import { useI18n } from '@/hooks/web/useI18n';

const { t } = useI18n();
const emit = defineEmits(['success']);

let id = ref<string>('');
let isUpdate = ref(true);
const { createMessage } = useMessage();
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  schemas: dataScopeFormSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
});

const [registerDrawer, { setDrawerProps, closeDrawer, changeLoading }] = useDrawerInner(
  async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      id.value = data.id;
      setFieldsValue({
        ...data.record,
        menuId: data.menuId,
      });
    } else {
      setFieldsValue({
        menuId: data.menuId,
      });
    }
  }
);

const getTitle = computed(() =>
  !unref(isUpdate) ? t('新增规则') : t('编辑规则')
);

async function handleSubmit() {
  try {
    const values = await validate();
    changeLoading(true);
    if (unref(isUpdate)) {
      await edit(values);
      createMessage.success(t('更新成功'));
    } else {
      await add(values);
      createMessage.success(t('保存成功'));
    }
    closeDrawer();
    emit('success');
  } finally {
    changeLoading(false);
  }
}
</script>
